package ilender.background;

import java.util.List;

import org.apache.ibatis.session.*;
import org.joda.time.DateTime;

import lombok.*;

import ilender.util.*;
import ilender.exceptions.UnauthorizedGraphActionException;
import ilender.facebook.FBNotification;
import ilender.facebook.FBUser;
import ilender.facebook.GraphAPI;
import ilender.mappers.*;
import ilender.models.*;

/**
 * Called periodically to run a check for overdue lends.
 *
 * Sends daily notifications to both borrower and lender.
 */
public class OverDueChecker implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub

		try (SqlSession session = MyBatisTools.openSession()) {
			OffersMapper offersMapper = session.getMapper(OffersMapper.class);
			val overDueOfersList = offersMapper.overDueOffers();

			GraphAPI graphAPI = GraphAPI.getInstance();

			for (val offer : overDueOfersList) {
				FBUser lender = graphAPI.getFBUser(offer.getItem()
						.getFacebook_user_id());
				FBUser borrower = graphAPI.getFBUser(offer.getRequest()
						.getFacebook_user_id());
				// send the notification
				// lender ..
				try {
					lender.notification()
						.setReference(offer)
						.setTemplate(
								String.format(
									"@[%s] needs to return the %s they borrowed from you.",
									borrower.id, offer.getItem()
									.getName())).post();
				} catch (UnauthorizedGraphActionException e) {
				}
				try {
					// borrower
					borrower.notification()
						.setReference(offer)
						.setTemplate(
								String.format(
									"You needs to return the %s you borrowed from @[%s].",
									offer.getItem().getName(),
									lender.id)).post();
				} catch (UnauthorizedGraphActionException e) {
				}

				// update that this offer had notified  .
				offer.setLast_notification_time(DateTime.now()) ;
				// save this offer in DB ..
				offer.save(offersMapper) ;
			}
			// commit at end out of the for .
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
